package top.zhongyy.controller;


import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import sun.security.x509.AVA;
import top.zhongyy.pojo.Comment;
import top.zhongyy.pojo.User;
import top.zhongyy.service.BlogService;
import top.zhongyy.service.CommentService;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Andy
 * @since 2021-03-25
 */
@Controller
public class CommentController {
    
    @Value("${comment.avatar}")
    private String avatar;
    
    @Autowired
    private CommentService commentService;
    
    @ApiOperation(value = "获取评论列表")
    @GetMapping("/comments/{blogId}")
    public String getComments(Model model, @PathVariable("blogId") Long blogId) {
        model.addAttribute("comments", commentService.getBlogComments(blogId));
        
        // fragment用法 ajax刷新,只刷新commentList
        return "blog :: commentList";
    }
    
    @ApiOperation(value = "发表评论")
    @PostMapping("/comments")
    public String postComment(Comment comment, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (comment.getParentCommentId() == -1) {
            comment.setParentCommentId(null);
        }
        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
            comment.setNickname(user.getNickname());
        } else {
            comment.setAvatar(avatar);
        }
        commentService.save(comment);
        return "redirect:/comments/" + comment.getBlogId();
        
    }
    
}

